<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { userUpdatePasswordService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

// 自定义校验：原密码和新密码不能一样
const checkNewPwdWithOldPwd = (rule, value, callback) => {
  if (value === pwdForm.value.old_pwd) {
    callback(new Error('新密码不能与原密码相同'))
  } else {
    callback()
  }
}

// 自定义校验：新密码和确认密码必须一样
const checkConfirmPwdWithNewPwd = (rule, value, callback) => {
  if (value !== pwdForm.value.new_pwd) {
    callback(new Error('确认密码与新密码不一致'))
  } else {
    callback()
  }
}

const formRules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: checkNewPwdWithOldPwd, trigger: 'blur' }
  ],
  re_pwd: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
    { validator: checkConfirmPwdWithNewPwd, trigger: 'blur' }
  ]
}

const pwdFormRef = ref(null)

const router = useRouter()
// 修改密码
const submitForm = async () => {
  // 预检验
  await pwdFormRef.value.validate()
  await userUpdatePasswordService(pwdForm.value)
  ElMessage.success('修改密码成功')
  //   密码修改成功后.退出账号重新登录
  //清空本地储存的token和用户信息
  userStore.setToken('')
  userStore.setUser({})

  //拦截到登陆页
  router.push('/login')
}

// 重置按钮
const resetForm = () => {
  pwdFormRef.value.resetFields()
}
</script>
<template>
  <page-container title="重置密码">
    <el-form
      :model="pwdForm"
      :rules="formRules"
      ref="pwdFormRef"
      label-width="120px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input
          style="width: 250px"
          v-model="pwdForm.old_pwd"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input
          style="width: 250px"
          v-model="pwdForm.new_pwd"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="re_pwd">
        <el-input
          style="width: 250px"
          v-model="pwdForm.re_pwd"
          type="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('pwdForm')"
          >修改密码</el-button
        >
        <el-button @click="resetForm('pwdForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </page-container>
</template>
